package com.theme.passport.controller;

import com.baidu.ueditor.ActionEnter;
import com.theme.common.base.ConfigConstant;
import com.theme.common.base.JSONHandler;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.request.param.UeditorRet;
import org.apache.commons.io.FilenameUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@RestController
@RequestMapping("/ueditor")
public class UEditorController {

    private static final String CONFIG = "config";
    private static final String UPLOAD_IMAGE = "uploadimage";
    private static final String CONFIG_PATH = "config.json";
    private static final String SAVE_PATH = "E:\\测试文件\\ueditor\\upload\\image";

    /**
     * 富文本server地址
     *
     * @param
     * @return
     * @throws
     */
    @RequestMapping
    public String ueditor(@RequestParam("action") String action, MultipartFile upfile) throws IOException {
        // Check action
        Assert.notNull(action, "Request api:[/ueditor] param:[action] is null");
        // Request action route
        switch (action) {
            case CONFIG:
                return readConfig();
            case UPLOAD_IMAGE:
                // Image save to local
                //String suffix = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf('.'));
                //StringBuffer filename = new StringBuffer().append(UUID.randomUUID()).append(suffix);
                //FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(SAVE_PATH + filename.toString()));
                // Image save to local
                // String suffix = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf('.'));
                // StringBuffer filename = new StringBuffer().append(UUID.randomUUID()).append(suffix);
                // FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(SAVE_PATH + filename.toString()));
                // return new UeditorRet(upfile.getOriginalFilename(),
                //         String.valueOf(upfile.getSize()),
                //         filename.toString(), suffix,
                //         filename.insert(0, "/ue/image/").toString()).toJsonString();
                //

                //上传文件
                String suffix = upfile.getOriginalFilename().substring(upfile.getOriginalFilename().lastIndexOf("."));
                String url = OSSFactory.build(null).uploadSuffix(upfile.getBytes(), suffix);

                URL urlTemp = new URL(url);
                // System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
                // System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
                // System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
                return new UeditorRet(upfile.getOriginalFilename(),
                        String.valueOf(upfile.getSize()),
                        FilenameUtils.getName(urlTemp.getPath()),
                        suffix,
                        url).toJsonString();
            default:
                throw new IllegalStateException("Request api:[/ue] param:[action] mismatching");
        }
    }


    /**
     * 读取配置信息 http方式
     *  String returnConfig = JSONHandler.getGson().toJson(config);
     * @return String
     * @throws throws IOException
     */
    private String readConfig() throws IOException {
        StringBuffer sb = new StringBuffer();   //sb用来存储txt文件里的内容
        String str = "";
        String mediaUrl = "https://theme2020.oss-cn-qingdao.aliyuncs.com/default/config.json";//文件路径我是从后台传的 就是 http://127.0.0.1......
        URL url = null;
        try {
            url = new URL(mediaUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader br = new BufferedReader(isr);
            while ((str = br.readLine()) != null) {
                sb.append(str);   //将读取的内容放入sb
            }
            br.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 字符串过滤（过滤注释信息、空格）
        String config = sb.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "").replace(" ", "");
        return config;
    }

    /**
     * 读取配置信息 本地local
     *
     * @return String
     * @throws throws IOException
     */
    private String readConfig1() throws IOException {
        StringBuffer sb = new StringBuffer();
        URL resource = UEditorController.class.getClassLoader().getResource(CONFIG_PATH);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(resource.getPath()));
        while (bufferedReader.ready()) {
            sb.append(bufferedReader.readLine());
        }
        // 字符串过滤（过滤注释信息、空格）
        String config = sb.toString().replaceAll("/\\*[\\s\\S]*?\\*/", "").replace(" ", "");
        return config;
    }

    /**
     * 图片读取地址  本地使用
     * Image save to local
     * @param
     * @return
     * @throws
     */
    @GetMapping("/image/{name}")
    public void preview(@PathVariable String name, HttpServletResponse response) {
        this.readImage(name, response);
    }

    /**
     * 读取图片（读取本地图片）
     *
     * @param name     图片名
     * @param response 响应对象
     */
    private void readImage(String name, HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream inputStream = new FileInputStream(SAVE_PATH + name)) {
            // Read IO Write outputStream
            byte[] buffer = new byte[4096];
            int count;
            while ((count = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @title: 测试接口可删 <tb>
     * @author: cuixinfu@51play.com <tb>
     * @date: 2021/11/5 11:50:52<tb>
     */
    @RequestMapping(value="/creatXml")
    public void creatXml(@RequestParam(value = "fileName") String fileName,
                         HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @title: 测试接口可删 <tb>
     * @author: cuixinfu@51play.com <tb>
     * @date: 2021/11/5 11:50:52<tb>
     */
    @RequestMapping(value="/generateXml")
    public void generateXml(@RequestParam(value = "fileName") String fileName,
                            HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
